<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\common\model\room;


use app\common\model\BaseModel;
use app\common\model\Building;
use app\common\model\Campus;
use app\common\model\user\User;


/**
 * 全院房间管理模型
 * Class RoomHospital
 * @package app\common\model\room
 */
class RoomHospital extends BaseModel {

    protected $name = 'room_hospital';

    public static function getTypeList($val = null) {
        $arr = [
            "0" => "空房",
            "1" => "在职",
            "2" => "离退休",
            "3" => "家属",
        ];
        if (is_numeric($val)) {
            return $arr[$val] ?? '';
        }
        return $arr;
    }

    public static function getLiftList($val = null) {
        $arr = [
            '0' => '免费',
            '50' => '分摊50%',
            '100' => '分摊100%',
        ];
        if (is_numeric($val)) {
            return $arr[$val] ?? '';
        }
        return $arr;
    }

    public function building() {
        return $this->hasOne(Building::class, 'id', 'bid');
    }

    public function campus() {
        return $this->hasOne(Campus::class, 'id', 'cid');
    }

    public function user() {
        return $this->hasOne(User::class, 'id', 'user_id');
    }

    public function allDevice() {
        return $this->hasMany(RoomHospitalDevice::class, 'rid', 'id');
    }

    public function sDeviceStat() {
        return $this->hasMany(RoomHospitalDevice::class, 'rid', 'id')->field([
            "*", "id as log_id",
        ])->where("device_type", 1);
    }

    public function dDeviceStat() {
        return $this->hasMany(RoomHospitalDevice::class, 'rid', 'id')->field([
            "*", "id as log_id",
        ])->where("device_type", 2);
    }

    public function allRoomStat() {
        return $this->hasMany(RoomHospital::class, 'user_id', 'user_id');
    }

    public function userRoomDeviceStat() {
        return $this->hasMany(RoomHospitalDevice::class, 'rid', 'id')->with([
            "device"
        ]);
    }

    public function userAllRoom() {
        return $this->hasMany(RoomHospital::class, "user_id", "user_id")
            ->field([
                "*",
                "lift_fee as room_lift_fee",
                "second_pressure_fee as room_second_pressure_fee",
            ])
            ->with([
                "campus", "building",
            ])
            ->withSum(["userRoomDeviceStat" => function ($query, &$alias) {
                $alias = 'room_s_use_total';
                $query->where('device_type', 1);
            }], "use_total")
            ->withSum(["userRoomDeviceStat" => function ($query, &$alias) {
                $alias = 'room_s_price';
                $query->where('device_type', 1);
            }], "price")
            ->withSum(["userRoomDeviceStat" => function ($query, &$alias) {
                $alias = 'room_s_total_fee';
                $query->where('device_type', 1);
            }], "total_fee")
            ->withCount(["userRoomDeviceStat" => function ($query, &$alias) {
                $alias = 'room_s_device_count';
                $query->where('device_type', 1);
            }])
            ->withSum(["userRoomDeviceStat" => function ($query, &$alias) {
                $alias = 'room_d_use_total';
                $query->where('device_type', 2);
            }], "use_total")
            ->withSum(["userRoomDeviceStat" => function ($query, &$alias) {
                $alias = 'room_d_price';
                $query->where('device_type', 2);
            }], "price")
            ->withSum(["userRoomDeviceStat" => function ($query, &$alias) {
                $alias = 'room_d_total_fee';
                $query->where('device_type', 2);
            }], "total_fee")
            ->withCount(["userRoomDeviceStat" => function ($query, &$alias) {
                $alias = 'room_d_device_count';
                $query->where('device_type', 2);
            }]);
    }

    public function data_append($user_ids_arr) {
        foreach ($user_ids_arr as $uia_key => $uia_val) {
            if (is_array($uia_val['room_ids'])) {
                $uia_val['room_count'] = count($uia_val['room_ids']);
                $uia_val['room_ids'] = implode(",", $uia_val['room_ids']);
            } else {
                $uia_val['room_count'] = count(explode(",", $uia_val['room_ids']));
            }

            if (isset($uia_val['is_log']) && 1 * $uia_val['is_log'] == 1) {
                $room_ids = explode(",", $uia_val['room_ids']);
                $uia_val['user_all_room'] = RoomHospitalLog::where('log_date', $uia_val['log_date'])
                    ->whereIn("rid", $room_ids)
                    ->where("log_time", $uia_val['log_time'])
                    ->select()->toArray();
            }

            foreach ($uia_val['user_all_room'] as $stat_key => $stat_val) {
                $new_stat_val = $stat_val;

                $new_stat_val['room_lift_fee'] = 1 * sprintf("%.6f", $new_stat_val['room_lift_fee'] * 1);
                $new_stat_val['room_second_pressure_fee'] = 1 * sprintf("%.6f", $new_stat_val['room_second_pressure_fee'] * 1);

                $new_stat_val['room_s_use_total'] = 1 * sprintf("%.6f", $new_stat_val['room_s_use_total'] * 1);
                $new_stat_val['room_s_price'] = 1 * sprintf("%.6f", $new_stat_val['room_s_price'] / ($new_stat_val['room_s_device_count'] <= 0 ? 1 : $new_stat_val['room_s_device_count']));
                $new_stat_val['room_s_total_fee'] = 1 * sprintf("%.2f", $new_stat_val['room_s_total_fee'] * 1);

                $new_stat_val['room_d_use_total'] = 1 * sprintf("%.6f", $new_stat_val['room_d_use_total'] * 1);
                $new_stat_val['room_d_price'] = 1 * sprintf("%.6f", ($new_stat_val['room_d_price'] / $new_stat_val['room_d_device_count'] <= 0 ? 1 : $new_stat_val['room_d_device_count']));
                $new_stat_val['room_d_total_fee'] = 1 * sprintf("%.2f", $new_stat_val['room_d_total_fee'] * 1);

                $ratf_arr = [
                    $new_stat_val['room_lift_fee'],
                    $new_stat_val['room_second_pressure_fee'],
//                    $new_stat_val['room_s_use_total'],
                    $new_stat_val['room_s_total_fee'],
//                    $new_stat_val['room_d_use_total'],
                    $new_stat_val['room_d_total_fee'],
                ];
                $new_stat_val['room_all_total_fee'] = sprintf("%.2f", array_sum($ratf_arr));
                $uia_val['user_all_room'][$stat_key] = $new_stat_val;
            }

            $new_uia_val = $uia_val;

            $new_uia_val['user_name'] = empty($new_uia_val['user_name']) ? ($uia_val['user'] ? $uia_val['user']['real_name'] : '') : $new_uia_val['user_name'];
            $new_uia_val['user_mobile'] = empty($new_uia_val['user_mobile']) ? ($uia_val['user'] ? $uia_val['user']['mobile'] : '') : $new_uia_val['user_mobile'];

            $new_uia_val['all_lift_fee'] = $this->array_sum_total($uia_val['user_all_room'], 'room_lift_fee', 1);
            $new_uia_val['all_second_pressure_fee'] = $this->array_sum_total($uia_val['user_all_room'], 'room_second_pressure_fee', 1);
            $new_uia_val['all_s_use_total'] = $this->array_sum_total($uia_val['user_all_room'], 'room_s_use_total', 1);
            $new_uia_val['all_s_total_fee'] = $this->array_sum_total($uia_val['user_all_room'], 'room_s_total_fee', 1);
            $new_uia_val['all_d_use_total'] = $this->array_sum_total($uia_val['user_all_room'], 'room_d_use_total', 1);
            $new_uia_val['all_d_total_fee'] = $this->array_sum_total($uia_val['user_all_room'], 'room_d_total_fee', 1);
            $atf_arr = [
                $new_uia_val['all_lift_fee'],
                $new_uia_val['all_second_pressure_fee'],
//                $new_uia_val['all_s_use_total'],
                $new_uia_val['all_s_total_fee'],
//                $new_uia_val['all_d_use_total'],
                $new_uia_val['all_d_total_fee'],
            ];
            $new_uia_val['all_total_fee'] = sprintf("%.2f", array_sum($atf_arr));

            $user_ids_arr[$uia_key] = $new_uia_val;
        }
        return $user_ids_arr;
    }

    public function getUserAttr($value, $data) {
        $user = [];
        $user[] = [
            "id" => "{$data['user_id']}" ?? 0,
            "user_id" => "{$data['user_id']}" ?? 0,
            "user_name" => $data['user_name'] ?? '',
            "user_mobile" => $data['user_mobile'] ?? '',
        ];
        return $user;
    }

    public function getAllDeviceAttr($value, $data) {
        $data['room_ids'] = empty($data['room_ids']) ? [] : explode(',', $data['room_ids']);
        $lists = RoomHospitalDevice::where([
            ["rid", "in", $data['room_ids']],
        ])->with(["campus", "building", "room", "device"])->select()->toArray();
        foreach ($lists as &$v) {
            $v['s_use_total'] = $v['s_price'] = $v['s_total_fee'] = $v['d_use_total'] = $v['d_price'] = $v['d_total_fee'] = 0;
            if ($v['device']['type'] == 1) {
                $v['s_use_total'] = $v['use_total'];
                $v['s_price'] = $v['price'];
                $v['s_total_fee'] = $v['total_fee'];
            } elseif ($v['device']['type'] == 2) {
                $v['d_use_total'] = $v['use_total'];
                $v['d_price'] = $v['price'];
                $v['d_total_fee'] = $v['total_fee'];
            }
        }
        return $lists;
    }

    public function getAllDeviceLogAttr($value, $data) {
        $room_ids = empty($data['room_ids']) ? [] : explode(',', $data['room_ids']);
        return RoomHospitalDeviceLog::field([
            "'" . count($room_ids) . "' as room_count",
            "sum( IF( device_type=1, use_total, 0) ) as all_s_use_total",
            "sum( IF( device_type=1, total_fee, 0) ) as all_s_total_fee",
            "sum( IF( device_type=2, use_total, 0) ) as all_d_use_total",
            "sum( IF( device_type=2, total_fee, 0) ) as all_d_total_fee",
            "( sum( total_fee ) + " . $data['all_lift_fee'] . " + " . $data['all_second_pressure_fee'] . " ) as all_total_fee",
        ])->where([
            ["rid", "in", $room_ids],
        ])->find()->toArray();
    }

    public function getCbIdsAttr($value, $data) {
        return [$data['cid'], $data['bid']];
    }

    public function getTypeTextAttr($value, $data) {
        return self::getTypeList($data['type']);
    }

    public function getLiftTypeTextAttr($value, $data) {
        if ($data['lift_type'] == '100') {
            $return_text = "平摊";
        } elseif ($data['lift_type'] == '0') {
            $return_text = "免费";
        } else {
            $return_text = $data['lift_type'] . "%";
        }
        return "分摊类型：" . $return_text;
    }

    public function getSortAttr($value, $data) {
        return $this->handle_sort($data['sort']);
    }

    public function userAllRoomDevice() {
        return $this->hasMany(RoomHospital::class, "user_id", "user_id")->with([
            "s_device_stat", "d_device_stat",
        ]);
    }

//    public function userAllRoomDeviceCeshi() {
//        return $this->hasManyThrough(RoomHospital::class, RoomHospital::class);
//    }

    public static function getPrintKeywordListRoom() {
        return [
            "index" => "序号",
            "name" => "房间",
            "user_name" => "住户",
            "room_d_use_total" => "总用电量",
            "room_d_price" => "平均电价",
            "room_d_total_fee" => "总电费",
            "room_s_use_total" => "总用水量",
            "room_s_price" => "平均水价",
            "room_s_total_fee" => "总水费",
            "room_lift_fee" => "电梯费",
            "room_second_pressure_fee" => "二次加压费",
            "room_all_total_fee" => "总费用",
        ];
    }

    public function getPrintKeywordListUserStat() {
        return [
            "user_name" => "姓名",
            "room_name" => "房间号",
            "room_d_total_fee" => "电费",
            "room_s_total_fee" => "水费",
            "time_text" => "日期",
        ];
    }

    public function getPrintKeywordListUserDevice() {
        return [
            "room_name" => "房间名",
            "user_name" => "姓名",

            "d_base_number" => "电表底数",
            "d_reading" => "电表读数",
            "d_use_total" => "用电度数",
            "d_price" => "电单价",
            "d_total_fee" => "总电费",

            "s_base_number" => "水表底数",
            "s_reading" => "水表读数",
            "s_use_total" => "用水度数",
            "s_price" => "水单价",
            "s_total_fee" => "总水费",

            "lift_fee" => "电梯费",
            "second_pressure_fee" => "加压费",

            "time_text" => "月份",
            "room_department" => "科室",
        ];
    }

}

